﻿using System;
using System.Windows;
using System.Windows.Input;
using System.Windows.Media.Animation;

namespace HeritageAcademy.Library.Controls
{
    /// <summary>
    /// Interaction logic for TableOfContentsView.xaml
    /// </summary>
    public partial class TableOfContentsView
    {
		#region Ctor 
        public TableOfContentsView()
        {
            InitializeComponent();
        }
		#endregion

		#region Event Handlers 
        private void Button_ClickToClose(object sender, RoutedEventArgs e)
        {
            IsOpen = false;
        }

        private void Rectangle_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            IsOpen = false;
        }
		#endregion

        #region IsOpen
        /// <summary>
        /// IsOpen Dependency Property
        /// </summary>
        public static readonly DependencyProperty IsOpenProperty =
            DependencyProperty.Register("IsOpen", typeof(bool), typeof(TableOfContentsView),
                new FrameworkPropertyMetadata(false,
                    new PropertyChangedCallback(OnIsOpenChanged)));

        /// <summary>
        /// Gets or sets the IsOpen property.  This dependency property 
        /// indicates ....
        /// </summary>
        public bool IsOpen
        {
            get { return (bool)GetValue(IsOpenProperty); }
            set { SetValue(IsOpenProperty, value); }
        }

        /// <summary>
        /// Handles changes to the IsOpen property.
        /// </summary>
        private static void OnIsOpenChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            ((TableOfContentsView)d).OnIsOpenChanged(e);
        }

        /// <summary>
        /// Provides derived classes an opportunity to handle changes to the IsOpen property.
        /// </summary>
        protected virtual void OnIsOpenChanged(DependencyPropertyChangedEventArgs e)
        {
            if ((bool)e.NewValue)
            {
                Visibility = Visibility.Visible;
                var open = Resources["Open"] as Storyboard;
                if (open != null) open.Begin(this);
            }
            else
            {
                Visibility = Visibility.Visible;
                var close = Resources["Close"] as Storyboard;

                EventHandler handler = null;
                //var handlerLocal = handler;
                handler = delegate(object s, EventArgs sbe)
                              {
                                  if (close != null) close.Completed -= handler;
                                  Visibility = Visibility.Collapsed;
                              };

                if (close != null)
                {
                    close.Completed += handler;
                    close.Begin(this);
                }
            }
        }
        #endregion
    }
}
